from django.db import models
from apps.chefs.models import DjChef
from django.utils.translation import gettext_lazy as _

class TimeSlot(models.Model):
    # 扩展时段选项：保留午餐/晚餐分类，增加排序值用于时间顺序判断
    PERIOD_CHOICES = (
        ('lunch', _('午餐')),   # 11:00-14:00
        ('dinner', _('晚餐')), # 18:00-20:00
    )
    
    # 状态选项保持不变
    STATUS_CHOICES = (
        ('available', _('可用')),
        ('booked', _('已预订')),
        ('unavailable', _('不可用')),
    )
    
    chef = models.ForeignKey(
        DjChef,
        on_delete=models.CASCADE,
        related_name='time_slots',
        verbose_name=_('厨师')
    )
    date = models.DateField(verbose_name=_('日期'))
    order = models.OneToOneField(
        'orders.Order',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='time_slot_info'
    )
    period = models.CharField(
        max_length=10,
        choices=PERIOD_CHOICES,
        verbose_name=_('时段')
    )
    status = models.CharField(
        max_length=15,
        choices=STATUS_CHOICES,
        default='available',
        verbose_name=_('状态')
    )
    # 新增：时段排序值（用于生成档期时确定顺序）
    period_order = models.PositiveSmallIntegerField(
        verbose_name=_('时段排序'),
        help_text=_('1=lunch, 2=dinner，用于按时间顺序排列')
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('创建时间'))
    updated_at = models.DateTimeField(auto_now=True, verbose_name=_('更新时间'))

    class Meta:
        verbose_name = _('档期')
        verbose_name_plural = _('档期')
        # 唯一约束：同一厨师同一天同一时段只能有一个档期
        unique_together = ('chef', 'date', 'period')
        # 按日期和时段排序（确保展示顺序正确）
        ordering = ['date', 'period_order']

    def __str__(self):
        return f"{self.chef.nickname} - {self.date} {self.get_period_display()}"

    def save(self, *args, **kwargs):
        # 自动设置时段排序值（lunch=1, dinner=2）
        self.period_order = 1 if self.period == 'lunch' else 2
        super().save(*args, **kwargs)